<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/13
 * Time: 11:45
 */

namespace App\Models\CacheModel;

use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use App\Models\Api\BaseCache;
use Exception;
use think\model\relation\HasMany;
use think\model\relation\HasOne;
use AstroTool\Cache\CacheManage;

/**
 * 校准生辰模型
 * Class Rectification
 * @package App\Models\CacheModel
 */
class Rectification extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_rectification';
    protected $cacheModel = 'rectification.rectification';

    /**
     * 关联校准生辰  事件模型
     * @return HasMany
     */
    public function events()
    {
        return $this->hasMany('RectificationEvent', 'reid', 'id');
    }

    /**
     * 关联校准生辰 结果模型
     * @return HasMany
     */
    public function result()
    {
        return $this->hasMany('RectificationResult', 'reid', 'id');
    }

    /**
     * @return HasOne
     */
    public function orders()
    {
        return $this->hasOne('Orders', 'reid', 'id', [], 'LEFT')->field('order_id,status,trade_type,pay_time,return_time,total_amount');
    }

    public function recode()
    {
        return $this->belongsTo('Recode', 'rid');
    }

    /**
     * 校准生辰保存或更新
     * @param $uid
     * @param $reid
     * @param array $data
     * @param array $event_data
     * @param array $result_data
     * @return int|mixed|string
     * @throws Exception
     */
    public function saveRec($uid, $reid, array $data, $event_data = [], $result_data = [])
    {
        $EventModel = new RectificationEvent();
        $ResultModel = new RectificationResult();
        if ($reid)
        {
            try
            {
                // 更新咨询师信息
                $this->where(['id' => $reid])->update($data);
                if ($event_data)
                {
                    $event_data = Util::array_push_element($event_data, ['reid' => $reid]);
                    $EventModel->UpdateData($reid, $event_data);
                }
                if ($result_data)
                {
                    $result_data = Util::array_push_element($result_data, ['reid' => $reid]);
                    $ResultModel->SaveData($result_data);
                }
            }
            catch (Exception $e)
            {
                $this->error = '更新校准生辰失败';
                return false;
            }
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $reid)->rmCache();
            CacheManage::getInstance()->setCacheConfig('rectification.rectification_event', $reid)->rmCache();
        } else
        {
            try
            {
                // 更新咨询师信息
                $reid = $this->insertGetId($data);
                if ($event_data)
                {
                    $event_data = Util::array_push_element($event_data, ['reid' => $reid]);
                    $EventModel->SaveData($event_data);
                }
            }
            catch (Exception $e)
            {
                $this->error = '保存校准生辰失败';
                return false;
            }
        }
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache('list');
        return $reid;
    }

    /**
     * 删除校准生辰数据和缓存
     * @throws Exception
     */
    public function DelData($uid, $reid)
    {
        try
        {
            // 更新咨询师信息
            $this->where(['id' => $reid, 'uid' => $uid])->update(['is_del' => 1]);

        }
        catch (Exception $e)
        {
            $this->error = '删除校准生辰失败';
            return false;
        }
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $reid)->rmCache();
        CacheManage::getInstance()->setCacheConfig('rectification.rectification_event', $reid)->rmCache();
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache('list');
        return true;
    }

    /**
     * 获取校准生辰详情
     * @param $reids
     * @return array
     * @throws Exception
     */
    public function getRecDetail($reids): array
    {
        $recs = $this->batchGetInfoByIds($reids, ['id', 'is_del', 'status', 'uid', 'rid', 'start_time', 'end_time', 'create_time', 'result_time', 'extend']);
        //获取校准生辰事件信息
        $events = (new RectificationEvent())->batchGetInfoByIds($reids, ['id', 'status', 'reid', 'time', 'type', 'desc']);
        //获取校准生辰结果信息
        $results = (new RectificationResult())->batchGetInfoByIds($reids, ['id', 'status', 'reid', 'time', 'score']);
        foreach ($recs as $k => $rec)
        {
            $recs[$k]['events'] = [];
            $recs[$k]['result'] = [];
            foreach ($events as $event)
            {
                if ($k == $event['reid'])
                {
                    $event['time'] = $event['time'] ? date('Y-m', $event['time']) : '';
                    $recs[$k]['events'][] = $event;
                }
            }
            foreach ($results as $result)
            {
                if ($k == $result['reid'])
                {
                    $result['time'] = $result['time'] ? date('Y/m.d H:i', $result['time']) : '';
                    $recs[$k]['result'][] = $result;
                }
            }
        }
        return $recs;
    }

    /**
     * 获取校准生辰列表
     * @param $uid
     * @return array | bool
     * @throws Exception
     */
    public function RectificationList($uid)
    {
//        $where = ['re.uid' => $uid, 're.is_del' => 0, 're.status' => ['in', [1, 2, 3]]];
//        $page = input('param.page');
//        try
//        {
//            $reids = $this
//                ->alias('re')
//                ->field('re.id')
//                ->join('wechat_backup_07_18_14_43_00.app_orders o', 're.id=o.reid')
//                ->where($where)
//                ->order('re.id', 'DESC')
//                ->paginate(10, false, ['page' => $page])->toArray();
//            $new_reids = array_column($reids['data'], 'id');
//        }
//        catch (Exception $e)
//        {
//            $reids = [
//                'total' => 0,
//                'per_page' => 10,
//                'current_page' => $page,
//                'last_page' => 1,
//                'data' => [],
//            ];
//            $new_reids = [];
//        }
//        $reids['data'] = $this->batchGetInfoByIds($new_reids, ['id', 'is_del', 'status', 'uid', 'rid', 'start_time', 'end_time', 'create_time', 'result_time']);
//        array_multisort(array_column($reids['data'], 'id'), SORT_NUMERIC, SORT_DESC, $reids['data']);
        $reids = $this->getListPage($uid, 'id', ['id', 'is_del', 'status', 'uid', 'rid', 'start_time', 'end_time', 'create_time', 'result_time']);
        return $reids;
    }

    /**
     * 数据库批量获取校准生辰数据
     * @param $ids
     * @param array $type [0=>uid,1=>type]
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType = 'DESC')
    {
        if ($ids)
        {
            $ids = is_array($ids) ? $ids : explode(',', $ids);
            $where = ['re.id' => ['in', $ids]];
        } else
        {
            //获取用户自己的档案
            $selfRecode = (new Recode())->getSelfRecodeFromDms($type[0]);
            $where = ['re.uid' => $type[0], 're.is_del' => 0, 're.status' => ['in', [1, 2, 3]], 're.rid' => $selfRecode ? current($selfRecode) : 0];
        }
        $field = 're.id,re.is_del,re.status,re.uid,re.rid,re.start_time,re.end_time,re.create_time,re.result_time,o.order_id,o.trade_type,o.total_amount,o.pay_time,o.return_time,o.status ostatus';
        try
        {
            $data = $this
                ->alias('re')
                ->field($field)
                ->join('wechat_backup_07_18_14_43_00.app_orders o', 're.id=o.reid', 'LEFT')
                ->where($where)
                ->order('re.id', $sortType)
                ->column($field, 're.id');
        }
        catch (Exception $e)
        {
            $data = [];
        }

        return $data;
    }
}
